/**
 * 
 */
package com.alstudio.ui.module.splash;

import java.io.File;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.app.ALSplashManager;
import com.alstudio.intent.ALIntentEvent;
import com.alstudio.pojo.module.local.LocalConfigure;
import com.alstudio.pojo.module.server.ServerInfo;
import com.alstudio.service.BackgroundService;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.module.account.GetAccountActivity;
import com.alstudio.ui.module.main.MainActivity;
import com.alstudio.utils.account.ALAccount;
import com.alstudio.utils.android.ALFileManager;
import com.alstudio.utils.log.ALLog;
import com.loovee.imaohu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class WelcomeActivity extends TitleBarActivity {

	private boolean inited = false;
	private DisplayImageOptions splashImageDisplayOptions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initData();
		setupView(this, getClass().getSimpleName());
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setContentView(R.layout.welcome_layout);
		setupSplash();
	}

	private void setupSplash() {
		if (ALSplashManager.getInstance().getSplashPath() != null) {
			if (ALFileManager.isFileExsit(ALSplashManager.getInstance()
					.getSplashPath())) {
				Uri uri = Uri.fromFile(new File(ALSplashManager.getInstance()
						.getSplashPath()));
				ALLocalEnv
						.getLocalEnv()
						.getImageLoader()
						.displayImage(uri.toString(),
								(ImageView) findViewById(R.id.background),splashImageDisplayOptions);
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		initData();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		// 初始化应用
		if (inited)
			return;
		inited = true;
		// initApp();
		registerAppInitCompletedReceiver();
		startApp();
		// startActivity();

		splashImageDisplayOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(false)
				// 加入内存缓存
				.cacheOnDisc(true)
				.displayer(new FadeInBitmapDisplayer(200))
				.bitmapConfig(Bitmap.Config.RGB_565).build();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#finish()
	 */
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		try {
			unregisterReceiver(appInitCompletedReceiver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void startApp() {
		// 开启后台服务
		Intent i = new Intent(this, BackgroundService.class);
		startService(i);

	}

	/**
	 * 初始化应用，打开数据库，读取配置文件，读取账号
	 */
	private void initApp() {

		String tmpName = ALLocalEnv.getLocalEnv().getDatabase()
				.loadPrivateAccount();
		if (!TextUtils.isEmpty(tmpName)) {
			ALLog.d("打开数据库" + tmpName);
			ALLocalEnv.getLocalEnv().getDatabase().loadDataBase(tmpName);
		} else {
			// 打开缺省滴数据库
			ALLocalEnv.getLocalEnv().getDatabase().loadDefaultDb();
			ALLog.d("打开缺省数据库");
		}

		// 是否已注销
		boolean isUserLogoff = ALLocalEnv.getLocalEnv().getDatabase()
				.loadSystemSetting();
		ALLog.d("读出来的注销标志是" + isUserLogoff);

		// 读取本地配置文件
		loadLocalConfigure();

		// 读取账号
		ALAccount account = ALLocalEnv.getLocalEnv().getDatabase()
				.loadMyAccount();
		account.setLogoff(isUserLogoff);
		ALLocalEnv.getLocalEnv().setAccount(account);
	}

	/**
	 * 从数据库中读取本地配置文件
	 */
	private void loadLocalConfigure() {
		// 从数据库中读取配置文件
		LocalConfigure mConfigure = ALLocalEnv.getLocalEnv().getDatabase()
				.getLocalConfigure();

		if (mConfigure.getServerInfo().getIMServerIP().length() == 0) {
			// 还没有存储到配置文件,初始化一个缺省的值
			ALLog.d("数据库中没有服务器地址,使用本地配置文件");
		} else {
			ALLog.d("###从数据库中读取的im地址为:"
					+ mConfigure.getServerInfo().getIMServerIP() + " http端口为:"
					+ mConfigure.getServerInfo().getHttpPort());
			ServerInfo temp = ALLocalEnv.getLocalEnv().getVersionConfig()
					.getServerInfo();
			temp.setIMServerIP(mConfigure.getServerInfo().getIMServerIP());
			temp.setIMSocketPort(mConfigure.getServerInfo().getIMSocketPort());

			temp.setMediaServerIp(mConfigure.getServerInfo().getMediaServerIp());
			temp.setMediaServerPort(mConfigure.getServerInfo()
					.getMediaServerPort());

			temp.setServerName(mConfigure.getServerInfo().getServerName());
		}
	}

	private void startActivity() {
		// 如果用户上次注销登录，那么跳转到登录界面
		mhandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				if (ALLocalEnv.getLocalEnv().getMyAccount().isLogoff()) {
					// 没有账号密码，跳转到登陆
					intent.setClass(WelcomeActivity.this,
							GetAccountActivity.class);
				} else if ((ALLocalEnv.getLocalEnv().getMyAccount()
						.getUserName() != null)) {
					intent.setClass(WelcomeActivity.this, MainActivity.class);

				} else {
					intent.setClass(WelcomeActivity.this,
							GetAccountActivity.class);
				}
				startActivity(intent);
				finish();
			}
		}, 2000);

	}

	private BroadcastReceiver appInitCompletedReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			startActivity();
		}
	};

	private void registerAppInitCompletedReceiver() {
		IntentFilter inf = new IntentFilter(ALIntentEvent.APP_INIT_COMPLETE);
		registerReceiver(appInitCompletedReceiver, inf);
	}

}
